package cn.schoolwow.quickdao.module.database.ddl.query.flow.property.getProperty;

import cn.schoolwow.quickdao.annotation.IdStrategy;
import cn.schoolwow.quickdao.domain.entity.Property;
import cn.schoolwow.quickdao.module.database.parent.domain.ResultSetConsumer;
import cn.schoolwow.quickdao.module.database.parent.flow.executor.ExecuteQueryConnectionFlow;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

import java.sql.ResultSet;

public class GetPropertyBySQLiteFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        String tableName = (String) flowContext.checkData("tableName");
        String columnName = (String) flowContext.checkData("columnName");

        flowContext.startFlow(new ExecuteQueryConnectionFlow())
                .putTemporaryData("name", "获取指定表指定字段信息")
                .putTemporaryData("sql", "PRAGMA table_info(`" + tableName + "`);")
                .putReturnData("resultSetConsumer",new ResultSetConsumer() {
                    @Override
                    public void consumeResultSet(ResultSet resultSet) throws Exception {
                        while (resultSet.next()) {
                            String resultSetColumnName = resultSet.getString("name");
                            if(resultSetColumnName.equalsIgnoreCase(columnName)){
                                Property property = new Property();
                                property.column = columnName;
                                property.columnType = resultSet.getString("type");
                                property.notNull = "1".equals(resultSet.getString("notnull"));
                                if (null != resultSet.getString("dflt_value")) {
                                    property.defaultValue = resultSet.getString("dflt_value");
                                }
                                if (1 == resultSet.getInt("pk")) {
                                    property.id = true;
                                    property.strategy = IdStrategy.AutoIncrement;
                                }
                                flowContext.putData("property", property);
                                break;
                            }
                        }
                    }
                })
                .execute();
    }

    @Override
    public String name() {
        return "获取数据库字段-SQLite数据库";
    }
}
